package com.cloud.common.interceptor;

import com.cloud.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    // 后续获取用户信息的关键字
    private static final String USERINFO_KEY = "user-info";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userInfo = request.getHeader(USERINFO_KEY);
        log.info("拦截器执行，传递的用户信息为：{}", userInfo);
        if (userInfo != null && !userInfo.isEmpty()) {
            UserContext.setContext(userInfo);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理传递的用户信息");
        UserContext.removeContext();
    }

}
